package com.module.zfb;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

public abstract class PayAction {


// 商户PID
	public static final String PARTNER = "2088121987158523";

//    public static final String PARTNER = "2088011448182375";//雪铁龙PID

//    public static final String PARTNER = "2088421333148991";//陆风PID
    // 商户收款账号
	public static final String SELLER = "tongyuanfang@aliyun.com";

//    public static final String SELLER = "bonengcw@163.com";//雪铁龙账号

//    public static final String SELLER = "2559117910@qq.com";//陆风账号
//     商户私钥，pkcs8格式
    public static final String RSA_PRIVATE = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALWlQ14GP1APRD+cYHyjB7FA54+v961prOaFXCH+86vIi49z7qnAEF49AsnVWb0RFr8H7Q+D5Wso4c1yB6MdMKdQUUs6ETVzG8xSsfMruGr9EsggDzWD4UL7HSnmoQRGdXggWMygS+omBq7Jhkirrj0P845qA/rsx6+VK0ELydMdAgMBAAECgYANSCA858gJWpRq8kw70M/nLg/AeeVqUKfL00SBV9sJXIiX3Ko+z0RjH6LsjyUYpf87yKCU2dgUldCs7QGR87hy48mRYFz/8LknvWUGBfP1+x5rtJPilekCaPTK6/9xyA0r6aXHBey20eUWNIFK8BzZ02rIgE5YSaRjonVpbSDgIQJBAOxU+kKLlRcvggJqe/D3/QeDMTHape32u6rvM1BGCcbWcoVeEwTVMYV+ZTZA+VoStKznGxVrytqmYJhp75fAETcCQQDEwzLyeuz7Rt6xCir/PXEAAp4JJu3wwXurQPz0rgI34KBhMWTJ2TE45eDISuVA83gh1z8Gch6MibwHz6Q6pXhLAkA3mxb3KVh/CBKS9vMKk47ZgajFjiiUgQVPBtEQBiquui5f6u6WqILqYf72cPs6kkQomofo1l/4akU4F1TkY7CpAkAekpHs+UqvNHDPo1vQ8vQG42E43NKl0PptPpjPT+ZKVl21HF6julqak6Vcmb6LXAkzgOVrE/pJLfGIaSwEbMeHAkBDmjlmvnbvb5rjrvxcrVapmqPJWeFCzChH66vLDv4Ac9eTpui0mDpl29SCWqayFI2hlqD1y9fnjIUFjpcC1Ukz";

    //雪铁龙私钥
//    public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAL20dOoyum1pLEPrBPgLvQzMMfuaDiXQCEDmxm2V03Guq1nwUx1BqkwByZQujq0fK3JdfFTSTQZQ6wOI3AM/yMyJZ17MYilEFDJiWrvQyo43gWFZG5IquhSXWA1+OU+2pUk2xXFNSmj8sKuMVu8WXNJ/NXowvrNHsBPAtfxwsyb7AgMBAAECgYABbJVkHLVhlOSMLft/kTb+HZpSdTmd9w3YzuK2d+V6eQE4T6GQGqoYn/rPbfoMOqus1B7W1C1X2suo3yIntBbhzuCQR4c4EKbqQaNpy58EuPrh/89IzFRmz31h4MfG2PPGyME8Becq3EymIuH315+C8R6ibdQC9K4UkZk67WGlIQJBAPm/+B2XjyAMc/QvMJzn/d6QLIIW/82xrZz3LVma4e3z7iyIZewByWS8bNhaJwPVOeLMkcnlq0jeKO6K8Mueme8CQQDCc86zNwqZHR/2qsw5tJisZkpVTy6paqu3rSwGnp9bGY7LyisMXx7UkSgNbdXQQ6ju13ObsRQflOjoIF2Jub+1AkBG6mSYen2Qexi9wFyMYS9r8AJDWiZ+kLIcfO8qn1kByR7bFEvkjMlTylEZydeENhp+tNm8u3M8eKCkw10GZF2PAkBdwxurPOImXG3aMhdRx+xKTPSQ2CKG3IG6io0NEBWFBvjc+TnyuDcUhn3Ko+iSiN1/dXIwY51xcQsxStHvpBp1AkEAxP+Ae2Y3ywa8+5WYzLRY2OHHJSmn+rNnOHrsK7XjYP5mNq3wGQs04GE60ckCB5xHAREy039qjY02yFqEjACBPg==";

    //陆风私钥

//    public static final String RSA_PRIVATE = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBALC2Pw08M8OYjX/FJYHiFdDywMuCXaIFdpuXxawM7PUV1rFi5fSPGeYp2UqBh1kZTyeOSxP42fwstdHj7wkD5dIGxQb2hDwDGlJQW9dci6fCUbcLHCpNrjFIEjxmBf91UYrdsis1RpmqYEeKGNBAfzCmn0ATVycC9SRf+3ccsT6XAgMBAAECgYEAgMwkgqoJdJvBLopr/xHhIs18dhhL1Ka0v01M100IfM3xEJNr1edjUh3YcXSdSPSoe8U7tY/gmeugjh3bALAllcwa6ahGzdIPF8cI9yOvsdDlecZIfUXHj+wKwGKSXRv85kLx2I2V3Ykrs6zYT11zfPFbgsnMD2T5nIAn3WxoM0kCQQDY+jRLZjnhwYq/OrcmTf3C2Yv+zLH7LJi8UvilvyOqg+HmcaLQb/ObYN7ctv1SN2aHnDi6YGIcHzVclNwERWTjAkEA0H4w3QKh2wx2m5/XYVS3n6MoQdU0R0+6jvWJVypM4L/1zxrIw0HZ32DsTihEzrhSsboXsR7kwIsIwWdhPWGhvQJBAInBEEJufIEf537RQEZJbbqvc3opazYUckPeSY6xc2tmn502uC+tY/RZ5CQs6VexZJ7kR//MAX3pMm+88pKjnBECQD6wAo8hMHtFRxBJwh+gsklMbFlG+p4KaeR8DRxpOo5FCWqI+h5DWXfhk4t4bh/dqfeIJYF68Xq3Ex3bsJAdH90CQQCB6FvObrkauutOj5HVVmAC99T4UPIxPrfeHnUi/iNv1bNTfS+OIThM7UiQYx1Y/b493XQSYRefhiEeueXEFRFY";

        // 支付宝公钥
    public static final String RSA_PUBLIC = "";

    private static final int SDK_PAY_FLAG = 1;

    private static final int SDK_CHECK_FLAG = 2;

    private Activity activity;

    public PayAction(Activity activity) {

        this.activity = activity;

    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case SDK_PAY_FLAG: {

                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(activity, "支付成功", Toast.LENGTH_SHORT).show();
                        onSuccess();
                        onEnd();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(activity, "支付结果确认中", Toast.LENGTH_SHORT).show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(activity, "支付失败", Toast.LENGTH_SHORT).show();
                            onEnd();
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(activity, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    /**
     * call alipay sdk pay. 调用SDK支付
     */
//	public void pay(String subject, String uid, String trade_no, String price,String account) throws Exception{
    public void pay(String subject, String uid, String trade_no, String price) throws Exception {

        if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE) || TextUtils.isEmpty(SELLER)) {

            new AlertDialog.Builder(activity).setTitle("警告").setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER").setPositiveButton("确定", null).show();

            return;

        }

        // 订单
        String orderInfo = getOrderInfo(subject, uid, trade_no, price);
//		String orderInfo = getOrderInfo(subject, uid, trade_no, price,account);

        // 对订单做RSA 签名
        String sign = sign(orderInfo);

        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(activity);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);

        payThread.start();

    }

    /**
     * create the order info. 创建订单信息
     */
//	public String getOrderInfo(String subject, String uid, String trade_no, String price,String account)
    public String getOrderInfo(String subject, String uid, String trade_no, String price) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + SELLER + "\"";
//		orderInfo += "&seller_id=" + "\"" + account + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + trade_no + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + uid + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + "101.201.143.219:8090/CPSP-SER2/notify/notify_url.json" + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

    /**
     * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
     */
    public String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
                Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    public String sign(String content) {
        return SignUtils.sign(content, RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    public String getSignType() {
        return "sign_type=\"RSA\"";
    }

    protected abstract void onSuccess();

    protected abstract void onEnd();

}
